package com.atguigu.ossservice.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.ossservice.service.FileService;
import com.atguigu.ossservice.utils.ConstantPropertiesUtil;
import com.atguigu.servicebase.handler.GuliException;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author gjl
 * @create 2021-04-02 10:30
 */
@Service
public class FileServiceImpl implements FileService {
    //上传文件
    @Override
    public String uploadFileOss(MultipartFile file) {

        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = ConstantPropertiesUtil.END_POINT;

       // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId =  ConstantPropertiesUtil.ACCESS_KEY_ID;

        String accessKeySecret =  ConstantPropertiesUtil.ACCESS_KEY_SECRET;

        String bucketName =  ConstantPropertiesUtil.BUCKET_NAME;


        //accessKeyId :LTAI4GGBBL5y7aj3c9w2ab1Y

        //accessKeySecret :WqLbUikSceOLV0H1sAgSdKFNJFq1qE


        OSS ossClient = null;

        InputStream inputStream = null;

        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
            inputStream = file.getInputStream();

            String fileName = file.getOriginalFilename();
            //UUID+fileName
            fileName = UUID.randomUUID().toString()+fileName;

            String filePath = new DateTime().toString("yyyy/MM/dd");

            fileName = filePath+"/"+fileName;

            // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;

            return url;

        } catch (IOException e) {
            e.printStackTrace();
            throw  new GuliException(20001,"上传文件失败");

        }



    }
}
